# -*- coding: utf-8 -*-
"""
/***************************************************************************
 MySetNodataValueDialog
                                 A QGIS plugin
 设置栅格影像nodata的值
                             -------------------
        begin                : 2014-11-27
        copyright            : (C) 2014 by 许石罗
        email                : xushiluo@163.com
 ***************************************************************************/

/***************************************************************************
 *                                                                         *
 *   This program is free software; you can redistribute it and/or modify  *
 *   it under the terms of the GNU General Public License as published by  *
 *   the Free Software Foundation; either version 2 of the License, or     *
 *   (at your option) any later version.                                   *
 *                                                                         *
 ***************************************************************************/
"""

from osgeo import gdal
from osgeo.gdalconst import *
from PyQt4 import QtCore, QtGui
from ui_mysetnodatavalue import Ui_MySetNodataValue
# create the dialog for zoom to point
from SetNodataUtils import SetNodataUtils

class MySetNodataValueDialog(QtGui.QDialog, Ui_MySetNodataValue):
    def __init__(self):
        QtGui.QDialog.__init__(self)
        # Set up the user interface from Designer.
        # After setupUI you can access any designer object by doing
        # self.<objectname>, and you can use autoconnect slots - see
        # http://qt-project.org/doc/qt-4.8/designer-using-a-ui-file.html
        # #widgets-and-dialogs-with-auto-connect
        self.setupUi(self)
        self.connectSignals()
        self.inFileName = None
        self.outputFileName = None


    def connectSignals(self):
        self.inputButton.clicked.connect(self.showOpenInputImageDialog)
        self.pushButtonSetNewValue.clicked.connect(self.setCurrentNodataValue)
        self.pushButtonGetCurrentValue.clicked.connect(self.getCurrentNodata)

        self.cancelButton.clicked.connect(self.close)
        self.okButton.clicked.connect(self.close)

    # 对话框显示时的事件处理函数
    def showEvent(self, event):
        super(MySetNodataValueDialog, self).showEvent(event)

        #获取所有栅格图层
        rasterLayers = SetNodataUtils.getRasterLayers()
        items=[]
        for layer in rasterLayers:
            items.append((SetNodataUtils.getExtendedLayerName(layer), layer))

        # 先清空QComboBox的所有对象
        self.comboBoxInput.clear()

        #将所以栅格图层添加到栅格图像列表中
        for (name, value) in items:
            self.comboBoxInput.addItem(name, value)

    #读取输入的栅格图像
    def showOpenInputImageDialog(self):
        fileName = str(QtGui.QFileDialog.getOpenFileName(self,
                                                        "Input Raster File:", "",
                                                        "Tiff Image (*.tif *.tiff);;Jpg Image (*.jpg)" ) )
        if len(fileName) is 0:
            return
        else:
            self.inFileName = fileName

        self.comboBoxInput.addItem(self.inFileName,self.inFileName)
        self.comboBoxInput.setCurrentIndex(self.comboBoxInput.count() - 1)

    #获取当前的栅格图像Nodata值
    def getCurrentNodata(self):
        self.inFileName = SetNodataUtils.getInputLayerPath( self.comboBoxInput.itemData(self.comboBoxInput.currentIndex()) )
        gdal.AllRegister()
        dataset = gdal.Open(self.inFileName, GA_ReadOnly)
        rasterBandNum = dataset.RasterCount
        if rasterBandNum==0:
            return

        nodataList=[]
        for i in range(rasterBandNum):
            currentBand_NodataValue = dataset.GetRasterBand(i+1).GetNoDataValue()
            nodataList.append(str(currentBand_NodataValue))
        tempStr = ",".join(nodataList)
        self.lineEditCurrentValue.setText(tempStr)
        dataset = None

    # 设置当前栅格图像的nodata值
    def setCurrentNodataValue(self):
        self.inFileName = SetNodataUtils.getInputLayerPath( self.comboBoxInput.itemData(self.comboBoxInput.currentIndex()) )
        gdal.AllRegister()
        dataset = gdal.Open(self.inFileName, GA_Update)
        rasterBandNum = dataset.RasterCount
        if rasterBandNum==0:
            return
        try:
            newNodataVal = float(self.lineEditNewValue.text())
        except ValueError:
            QtGui.QMessageBox.critical(self, "", "the input nodata value is incorrent!")
            return

        if newNodataVal is None or newNodataVal == "":
            return
        for i in range(rasterBandNum):
            currentBand_NodataValue = dataset.GetRasterBand(i+1).SetNoDataValue(newNodataVal)

        dataset = None

        self.getCurrentNodata()
